<template lang="pug">
  #amap
    #container
</template>

<script type="text/ecmascript-6">
  // import wgs2mars from 'wgs2mars'
  import amapConfig from './amap.conf'
  /**
   * 高德地图组件，基于vue2.0 es6标准
   * created by lvjia on 20170318
   */
  export default {
    name: 'vue-amap',
    data () {
      return {
        // Global引用
        _globalAmap: null,
        // 本地map实例
        _map: null,
        // 本地geolocation实例
        _geolocation: null,
        // debug use
        poiList: '',
        markers: []
      }
    },
    props: {},
    methods: {
      /**
       * 初始化本地map实例，传入脚本运行后挂载的BMap对象
       * @param BMap
       */
      _initMap (AMap) {
        // var map, geolocation
        this._globalAmap = AMap
        // 加载地图，调用浏览器定位服务
        this._map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 16
        })
        this._map.plugin(['AMap.ToolBar'], () => {
          // 加载工具条
          let tool = new AMap.ToolBar({
            position: 'RT'
          })
          this._map.addControl(tool)
        })
        this.setCenterMarker(AMap)
//        this.setToolbar()
        // 定位
        this._map.plugin('AMap.Geolocation', () => {
          this._geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认:true
            timeout: 10000,          // 超过10秒后停止定位，默认：无穷大
            // noIpLocate: 3,
            // noGeoLocation: 3,
            // convert: true,
            // panToLocation: false,
            buttonOffset: new AMap.Pixel(10, 100), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            // zoomToAccuracy: true,      // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition: 'LT'
            // showCircle: true,
            // showMarker: true
          })
          this._map.addControl(this._geolocation)
          this._geolocation.getCurrentPosition()
          AMap.event.addListener(this._geolocation, 'complete', this.onComplete) // 返回定位信息
          AMap.event.addListener(this._geolocation, 'error', this.onError)      // 返回定位出错信息
        })
      },
      // 解析定位结果
      onComplete (data) {
        this.$store.dispatch('amapSetCurrentPosition', data.position)
        this.searchCity()
        // this.getCenter()
        this.searchLocationData()
        this.searchCloudData()
        /*
        // this.centerMarker.setPosition(this._map.getCenter())
        // console.log('oncomplete' + data.position.getLng() + data.position.getLat())
        // let gcjloc = wgs2mars.transformFromWGSToGCJ(data.position.getLng(), data.position.getLat())
        // this._map.panTo([gcjloc.lng, gcjloc.lat])
        // this._map.panTo([data.position.getLng(), data.position.getLat()])
        // this._map.panTo([110.1887512207, 20.3214479928])
        */
        // 监听缩放事件
        this.$store.dispatch('amapSetZoom', this._map.getZoom())
        this._globalAmap.event.addListener(this._map, 'zoomend', () => {
          this.$store.dispatch('amapSetZoom', this._map.getZoom())
          this.clearMarkers()
          // this.searchCity()
          this.searchLocationData()
          this.searchCloudData()
        })
        this._map.on('movestart', (e) => {
          this.clearMarkers()
        })
        // 监听地图移动事件
        this._map.on('moveend', (e) => {
          // window.alert(JSON.stringify(e))
          this.$store.dispatch('appSetShowMap')
          this.clearMarkers()
          this.searchCity()
          // this.centerMarker.setPosition(this._map.getCenter())
          this.getCenter()
          this.searchLocationData()
          this.searchCloudData()
        })
      },
      // 解析定位错误信息
      onError (data) {
        // document.getElementById('tip').innerHTML = '定位失败'
      },
      setToolbar () {
        this._map.plugin(['AMap.ToolBar'], () => {
          this._map.addControl(new this._globalAmap.ToolBar())
        })
        if (location.href.indexOf('&guide=1') !== -1) {
          this._map.setStatus({scrollWheel: false})
        }
      },
      searchLocationData () {
        // 搜索周边
        this._globalAmap.service(['AMap.PlaceSearch'], () => {
          // 构造地点查询类
          let placeSearch = new this._globalAmap.PlaceSearch({
            pageSize: 10,
            // 兴趣点类别，多个类别用“|”分割，如“餐饮|酒店|电影院”
            // POI搜索类型共分为以下20种：
            // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
            // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
            // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
            // 默认值：餐饮服务、商务住宅、生活服务
            type: '风景名胜|商务住宅|科教文化服务',
            pageIndex: 1
            // city: '海口市' // 城市
            // map: this._map
          })
          placeSearch.searchNearBy('', this._map.getCenter(), 1000, (status, result) => {
            if (status === 'no_data') {
            } else {
            }
            // 发送当前周边地址信息
            this.$store.dispatch('amapSetLocationSearchResults', result)
          })
        })
      },
      setCenterMarker (AMap) {
        // 地图中心标记
        AMap.CenterControlDiv = function () {
        }

        // 计算容器的中心点
        let container = document.getElementById('container')
        // window.alert(container.offsetWidth)
        let centerX = Math.round(container.offsetWidth / 2)
        let centerY = Math.round(container.offsetHeight / 2)

        AMap.CenterControlDiv.prototype = {
          addTo: function (map, dom) {
            dom.appendChild(this._getHtmlDom(map))
          },
          _getHtmlDom: function (map) {
            this.map = map
            // 创建一个能承载控件的<div>容器
            let controlUI = document.createElement('DIV')
            controlUI.className = 'center'
            // 设置控件的位置
            controlUI.style.position = 'absolute'
            controlUI.style.left = (centerX - 10) + 'px'
            controlUI.style.top = (centerY - 20) + 'px'
            controlUI.style.zIndex = '300'
            // 设置控件字体样式
            // controlUI.innerHTML = `<img width="20" height="20" src="http://download.easyicon.net/png/1182024/128/">`
            controlUI.innerHTML = `              <svg version="1.1" xmlns="http://www.w3.org/2000/svg">
              <rect id="pin-body" x="9.1" y="19.5" fill="#222222" width="4" height="21.9"/>
              <circle id="pin-header" fill="#222222" cx="11.1" cy="10.9" r="9.6"/>
              <circle id="pin-hole" fill="#FFFFFF" cx="11.1" cy="10.9" r="5.1"/>
              </svg>`
            return controlUI
          }
        }
        let centerControl = new AMap.CenterControlDiv(this._map)
        this._map.addControl(centerControl)
      },
      searchCloudData () {
        // 搜索cloud poi
        // 按照zoom level 设置查询条件
        let searchOptions
        // window.alert(this.zoom)
//        if (this.zoom <= 12) {
          // 查询区域总和
//          searchOptions = {
//            // map: this._map,
//            // panel: 'panel',
//            keywords: '',
//            filter: 'type:1',
//            pageSize: 10
//          }
//         return
//       } else {
          // 查询单点
        searchOptions = {
          // map: this._map,
          // panel: 'panel',
          keywords: '',
          filter: 'type:0',
          pageSize: 10
          // orderBy: '_id:ASC'
        }
//        }
        // 获取当前视口bounds
        // let bounds = this._map.getBounds()

        // window.alert(JSON.stringify(searchOptions))
        // 加载CloudDataSearch服务插件
        this._globalAmap.service(['AMap.CloudDataSearch'], () => {
          let search = new this._globalAmap.CloudDataSearch(amapConfig.MAP_KEY, searchOptions)
          // search.searchInPolygon([bounds.getNorthEast(), bounds.getSouthWest()], (status, result) => {
          search.searchNearBy(this._map.getCenter(), 1000, (status, result) => {
            // 清除上一次的marker
            // this._map.remove(this.markers)
            // 显示marker
            this.poiList = JSON.stringify(result)
            if (status === 'no_data' || this.zoom <= 12) {
            } else {
              for (let i = 0; i < result.datas.length; i++) {
                let marker = new this._globalAmap.Marker({
                  map: this._map,
                  position: result.datas[i]._location,
                  // title: result.datas[i].count
                  content: `<div class="map-marker"><p>${result.datas[i].count}</p><div class="triangle-down"></div><div class="shadow-wrapper"><div class="triangle-shadow"></div></div></div>`
                })
                // 添加事件响应
                if (result.datas[i].type === 1) {
                  marker.on('click', () => {
                    this._map.setZoomAndCenter(16, result.datas[i]._location)
                  })
                } else {
                  marker.on('click', () => {
                    this.$store.dispatch('amapSetLocationId', result.datas[i].location_id)
                    this.$store.dispatch('amapSetLocationName', result.datas[i]._name)
                    this.$store.dispatch('appSetShowList')
                  })
                }
                this.markers.push(marker)
              }
            }
            // 发送当前周边地址信息
            this.$store.dispatch('amapSetPoiSearchResults', result)
          })
        })
      },
      searchCity () {
        // 查询城市信息
        // window.alert('searchCity')
        this._map.getCity((data) => {
          if (data['province'] && typeof data['province'] === 'string') {
            // 发送当前城市信息
            // console.log(JSON.stringify(data))
            if (data.city !== '') {
              // 查询当前城市行政区
              this.$store.dispatch('amapSetCurrentCity', data)
              this.searchDistrict(data.city)
            } else if (data.province === '北京市' ||
              data.province === '天津市' ||
              data.province === '上海市' ||
              data.province === '重庆市') {
              // 直辖市
              let modifiedData = {
                province: data.province,
                city: data.province,
                district: data.district,
                citycode: data.citycode
              }
              this.$store.dispatch('amapSetCurrentCity', modifiedData)
              this.searchDistrict(data.province + '市辖区')
            } else {
              // 没有地级市
              let modifiedData = {
                province: data.province,
                city: data.district,
                district: data.district,
                citycode: data.citycode
              }
              this.$store.dispatch('amapSetCurrentCity', modifiedData)
              this.searchDistrict(data.district)
            }
          }
        })
      },
      searchDistrict (city) {
        // 缩放级别小于等于12时查询
        // window.alert('searchDis:' + city + 'zoom:' + this.zoom)
        if (this.zoom <= 12) {
          // 加载行政区划插件
          this._globalAmap.service('AMap.DistrictSearch', () => {
            var opts = {
              subdistrict: 1,   // 返回下一级行政区
              level: 'city',  // 查询行政级别为 市
              showbiz: false
            }
            // 实例化DistrictSearch
            let district = new this._globalAmap.DistrictSearch(opts)
            // district.setLevel('district');
            // 行政区查询
            district.search(city, (status, result) => {
              // // console.log(city)
              // // console.log(JSON.stringify(result))
              this.$store.dispatch('amapSetDistrictSearchResults', result)
              this.countByDistrict(result)
            })
          })
        }
      },
      countByDistrict (districtResultData) {
        // // console.log(JSON.stringify(districtResultData))
        let searchOptions = {
          // map: this._map,
          pageSize: 5,
          orderBy: '_id:ASC'
        }
        // 加载CloudDataSearch服务插件
        this._globalAmap.service(['AMap.CloudDataSearch'], () => {
          // 测试key 58d215ec305a2a68100c996e
          // let search = new this._globalAmap.CloudDataSearch('58d215ec305a2a68100c996e', searchOptions)
          // 正式key
          let search = new this._globalAmap.CloudDataSearch(amapConfig.MAP_KEY, searchOptions) // 构造云数据检索类
          let countResults = []
          // window.alert(districtResultData.districtList[0].districtList.length)
          if (districtResultData.districtList[0].districtList) {
            // // console.log(districtResultData.districtList[0].districtList.length)
            for (let i = 0; i < districtResultData.districtList[0].districtList.length; i++) {
              if (districtResultData.districtList[0].districtList[i].level !== 'district') {
                continue
              }
              search.searchByDistrict(districtResultData.districtList[0].name + districtResultData.districtList[0].districtList[i].name, (status, result) => {
                // window.alert(status)
                // window.alert(JSON.stringify(result))
                // // console.log(districtResultData.districtList[0].districtList[i].name)
                // // console.log(JSON.stringify(result))
                let count = 0
                if (status === 'complete') {
                  count = result.count
                }
                let countResult = {
                  name: districtResultData.districtList[0].districtList[i].name,
                  count: count
                }
                let p1 = districtResultData.districtList[0].districtList[i].name
                let p2 = count > 0 ? count + '个地点' : '暂无发布'

                let marker = new this._globalAmap.Marker({
                  map: this._map,
                  position: districtResultData.districtList[0].districtList[i].center,
                  // title: result.datas[i].count
                  content: `<div class="map-district-marker"><p>${p1}</p><p>${p2}</p></div>`
                })
                // 添加事件响应
                marker.on('click', () => {
                  this._map.setZoomAndCenter(16, districtResultData.districtList[0].districtList[i].center)
                })
                this.markers.push(marker)
                countResults.push(countResult)
              })
            }
          } else {
            // 没有区
            search.searchByDistrict(districtResultData.districtList[0].name, (status, result) => {
              // window.alert(status)
              // window.alert(JSON.stringify(result))
              let count = 0
              if (status === 'complete') {
                count = result.count
              }
              let countResult = {
                name: districtResultData.districtList[0].name,
                count: count
              }
              let p1 = districtResultData.districtList[0].name
              let p2 = count > 0 ? count + '个地点' : '暂无发布'
              let marker = new this._globalAmap.Marker({
                map: this._map,
                position: districtResultData.districtList[0].center,
                // title: result.datas[i].count
                content: `<div class="map-district-marker"><p>${p1}</p><p>${p2}</p></div>`
              })
              // 添加事件响应
              marker.on('click', () => {
                this._map.setZoomAndCenter(16, districtResultData.districtList[0].center)
              })
              this.markers.push(marker)
              countResults.push(countResult)
            })
          }
          this.$store.dispatch('amapSetDistrictCountResults', countResults)
        })
      },
      getCenter () {
        // 同步当前地图中心点
        this.$store.dispatch('amapSetMapCenter', this._map.getCenter())
      },
      clearMarkers () {
        this._map.remove(this.markers)
      },
      // 手动刷新定位信息
      refresh () {
        this._geolocation.getCurrentPosition()
      },
      /**
       * 初始化地图脚本
       * @returns {*}
       */
      _loadScript () {
        if (!global.AMap) {
          return new Promise((resolve, reject) => {
            global._init = function () {
              resolve(global.AMap)
              global.document.body.removeChild($script)
              global._init = null
            }
            const $script = document.createElement('script')
            global.document.body.appendChild($script)
            // 配置web key 6a46e03bea82e6046f9388f6b6f4539b
            // 测试key
            // $script.src = 'http://webapi.amap.com/maps?v=1.3&key=6a46e03bea82e6046f9388f6b6f4539b&callback=_init'
            // 正式key
            $script.src = 'http://webapi.amap.com/maps?v=1.3&key=' + amapConfig.APP_KEY + '&callback=_init'
          })
        }
        return Promise.resolve(global.AMap)
      }
    },
    created () {
      // console.log('created')
      const {_loadScript, _initMap} = this
      _loadScript().then(_initMap)
    },
    computed: {
      // 获取store中refresh标志
      needRefresh () {
        return this.$store.state.amap.status.needRefresh
      },
      // 获取省信息
      city () {
        // console.log('123' + this.$store.state.amap.newCity.city)
        return this.$store.state.amap.newCity.city
      },
      // zoom
      zoom () {
        return this.$store.state.amap.zoom
      },
      center () {
        return this.$store.state.amap.mapCenter
      },
      locationKeyword () {
        return this.$store.state.amap.locationSearchKeyword
      }
    },
    watch: {
      // 监视是否需要刷新
      needRefresh: function () {
        if (this.needRefresh) {
          // refresh
          this.refresh()
          // set to false
          this.$store.dispatch('amapRefreshCompleted')
        }
      },
      city: function () {
        this._map.setCity(this.city)
      },
      zoom: function () {
        // console.log('zoom changed')
        this._map.setZoom(this.zoom)
      },
      center: function () {
        this._map.setCenter(this.center)
      },
      locationKeyword: function () {
        // 搜索周边
        this._globalAmap.service(['AMap.PlaceSearch'], () => {
          // 构造地点查询类
          console.log(this.$store.state.amap.currentCity.city)
          let placeSearch = new this._globalAmap.PlaceSearch({
            pageSize: 10,
            type: '商务住宅',
            pageIndex: 1,
            city: this.$store.state.amap.currentCity.city // 城市
            // map: this._map
          })
          placeSearch.search(this.locationKeyword, (status, result) => {
            // console.log(result)
            if (status === 'no_data') {
            } else {
              // 发送当前周边地址信息
              this.$store.dispatch('amapSetLocationSearchResults', result)
              // console.log(result)
            }
          })
        })
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import './amap.styl'
</style>

